package com.geekbg.zookeeper.distributedqueue;

import com.google.common.collect.Queues;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * @author pizhihui
 * @date 2023-02-28 10:48
 */
public class GuavaQueue {

    private static int NUM_ELEMENTS = 10;

    private static int TIME_OUT = 5;

    public static void main(String[] args) {

        final BlockingQueue queue = new LinkedBlockingQueue();
        new Thread(new Runnable() {
            public void run() {
                long num = 1L;
                while (true) {
                    try {
                        queue.put(num);
                        num++;
                        long time = (long) (Math.random() * 1000);
                        Thread.sleep(time);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();

        while (true) {
            try {
                List list = new ArrayList(NUM_ELEMENTS);
                Queues.drain(queue, list, NUM_ELEMENTS, TIME_OUT, TimeUnit.SECONDS);
                System.out.println(list + ", size:" + list.size());
                //执行存库动作
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}

